<?php

namespace app\api\controller;

use app\api\model\DiChatSessions as ModelDiChatSessions;
use think\Controller;
use think\Db;
use app\common\model\DiChatSessions;
use app\common\library\Auth;
use app\common\controller\Api;

class Chat extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 获取或创建聊天会话
     * @param int $jobId 兼职任务ID
     * @param int $employerId 雇主用户ID
     */
    public function getSession()
    {
        $jobId = $this->request->param('job_id/d');
        $employerId = $this->request->param('employer_id/d');
        $workerId = $this->auth->id; // 当前用户（乙方）ID

        if (!$jobId || !$employerId) {
            return json(['code' => 1, 'msg' => '参数缺失']);
        }

        // 检查会话是否已存在
        $session = ModelDiChatSessions::where([
            'job_id' => $jobId,
            'employer_id' => $employerId,
            'worker_id' => $workerId
        ])->find();

        // 若不存在则创建新会话
        if (!$session) {
            $sessionId = ModelDiChatSessions::insertGetId([
                'job_id' => $jobId,
                'employer_id' => $employerId,
                'worker_id' => $workerId,
                'status' => 1,
                'create_time' => time(),
                'update_time' => time()
            ]);
            $session = ModelDiChatSessions::get($sessionId);
        }

        return json([
            'code' => 0,
            'msg' => '获取成功',
            'data' => [
                'session_id' => $session->id,
                'job_id' => $session->job_id,
                'employer_id' => $session->employer_id,
                'worker_id' => $session->worker_id
            ]
        ]);
    }

    /**
     * 发送消息
     * @param int $sessionId 会话ID
     * @param string $content 消息内容
     */
    public function sendMessage()
    {
        $sessionId = $this->request->param('session_id/d');
        $content = $this->request->param('content/s');
        $senderId = $this->auth->id; // 发送者ID

        if (!$sessionId || empty($content)) {
            return json(['code' => 1, 'msg' => '参数缺失']);
        }

        // 验证会话是否存在且当前用户参与了会话
        $session = ModelDiChatSessions::where('id', $sessionId)
            ->where(function ($query) use ($senderId) {
                $query->where('employer_id', $senderId)
                    ->orWhere('worker_id', $senderId);
            })
            ->find();

        if (!$session) {
            return json(['code' => 2, 'msg' => '会话不存在或无权限']);
        }

        // 确定接收者ID
        $receiverId = ($session->employer_id === $senderId)
            ? $session->worker_id
            : $session->employer_id;

        // 记录消息到数据库
        $messageId = Db::name('chat_messages')->insertGetId([
            'session_id' => $sessionId,
            'sender_id' => $senderId,
            'receiver_id' => $receiverId,
            'content' => $content,
            'type' => 1, // 1=文本消息
            'is_read' => 0,
            'create_time' => time()
        ]);

        // 更新会话最后消息时间
        ModelDiChatSessions::where('id', $sessionId)
            ->update(['last_message_time' => time()]);

        // 更新未读计数（使用数据库原子操作）
        Db::name('chat_unread')
            ->where('user_id', $receiverId)
            ->where('session_id', $sessionId)
            ->setInc('unread_count', 1);

        // 通过 GatewayClient 推送消息（需确保 GatewayWorker 服务已启动）
        try {
            \GatewayClient\Gateway::$registerAddress = '127.0.0.1:1236';
            if (\GatewayClient\Gateway::isUidOnline($receiverId)) {
                \GatewayClient\Gateway::sendToUid($receiverId, json_encode([
                    'type' => 'chat',
                    'session_id' => $sessionId,
                    'message_id' => $messageId,
                    'sender_id' => $senderId,
                    'content' => $content,
                    'create_time' => time()
                ]));
            }
        } catch (\Exception $e) {
            // 记录日志，不影响消息发送结果
            \think\Log::error('Gateway推送失败: ' . $e->getMessage());
        }

        return json([
            'code' => 0,
            'msg' => '发送成功',
            'data' => [
                'message_id' => $messageId,
                'session_id' => $sessionId,
                'content' => $content,
                'create_time' => time()
            ]
        ]);
    }
    /**
     * 获取消息列表
     * @param int $sessionId 会话ID
     * @param int $page 页码
     * @param int $limit 每页数量
     */
    public function getMessageList()
    {
        $sessionId = $this->request->param('session_id/d');
        $page = $this->request->param('page/d', 1);
        $limit = $this->request->param('limit/d', 20);

        if (!$sessionId) {
            return json(['code' => 1, 'msg' => '参数缺失']);
        }

        // 查询消息列表
        $messages = Db::name('chat_messages')
            ->where('session_id', $sessionId)
            ->order('create_time', 'asc')
            ->page($page, $limit)
            ->select();

        // 将当前用户的消息标记为已读
        $userId = $this->auth->id;
        Db::name('chat_messages')
            ->where('session_id', $sessionId)
            ->where('receiver_id', $userId)
            ->where('is_read', 0)
            ->update([
                'is_read' => 1,
                'read_time' => time()
            ]);

        // 重置未读计数
        Db::name('chat_unread')
            ->where('user_id', $userId)
            ->where('session_id', $sessionId)
            ->update(['unread_count' => 0]);

        return json([
            'code' => 0,
            'msg' => '获取成功',
            'count' => count($messages),
            'data' => $messages
        ]);
    }

    /**
     * 获取或创建群聊房间
     * @param int $jobId 兼职任务ID
     */
    public function getGroupRoom()
    {
        $jobId = $this->request->param('job_id/d');
        $userId = $this->auth->id; // 当前用户ID
        $userType = $this->request->param('user_type/d', 2); // 1:雇主,2:工人

        if (!$jobId) {
            return json(['code' => 1, 'msg' => '参数缺失']);
        }

        // 检查房间是否已存在
        $room = Db::name('chat_rooms')
            ->where('job_id', $jobId)
            ->find();

        // 若不存在则创建新房间
        if (!$room) {
            $roomId = Db::name('chat_rooms')->insertGetId([
                'job_id' => $jobId,
                'name' => '任务#' . $jobId . '群聊',
                'creator_id' => $userId,
                'status' => 1,
                'create_time' => time(),
                'update_time' => time()
            ]);
            $room = Db::name('chat_rooms')->find($roomId);

            // 添加创建者到房间成员
            Db::name('chat_room_members')->insert([
                'room_id' => $roomId,
                'user_id' => $userId,
                'user_type' => $userType,
                'join_time' => time()
            ]);
        } else {
            // 检查用户是否已在房间中
            $isMember = Db::name('chat_room_members')
                ->where('room_id', $room['id'])
                ->where('user_id', $userId)
                ->find();

            // 不在房间中则添加
            if (!$isMember) {
                Db::name('chat_room_members')->insert([
                    'room_id' => $room['id'],
                    'user_id' => $userId,
                    'user_type' => $userType,
                    'join_time' => time()
                ]);
            }
        }

        return json([
            'code' => 0,
            'msg' => '获取成功',
            'data' => [
                'room_id' => $room['id'],
                'job_id' => $room['job_id'],
                'name' => $room['name']
            ]
        ]);
    }

    /**
     * 发送群聊消息
     * @param int $roomId 房间ID
     * @param string $content 消息内容
     */
    public function sendGroupMessage()
    {
        $roomId = $this->request->param('room_id/d');
        $content = $this->request->param('content/s');
        $senderId = $this->auth->id; // 发送者ID

        if (!$roomId || empty($content)) {
            return json(['code' => 1, 'msg' => '参数缺失']);
        }

        // 验证房间是否存在且当前用户是房间成员
        $isMember = Db::name('chat_room_members')
            ->where('room_id', $roomId)
            ->where('user_id', $senderId)
            ->find();

        if (!$isMember) {
            return json(['code' => 2, 'msg' => '房间不存在或无权限']);
        }

        // 记录消息到数据库
        $messageId = Db::name('chat_messages')->insertGetId([
            'session_id' => 0, // 群聊消息session_id为0
            'sender_id' => $senderId,
            'receiver_id' => 0, // 群聊消息receiver_id为0
            'content' => $content,
            'type' => 1, // 1=文本消息
            'is_read' => 0,
            'is_group' => 1, // 标记为群聊消息
            'room_id' => $roomId, // 房间ID
            'create_time' => time()
        ]);

        // 更新房间最后消息时间
        Db::name('chat_rooms')
            ->where('id', $roomId)
            ->update(['last_message_time' => time()]);

        // 获取房间所有成员
        $members = Db::name('chat_room_members')
            ->where('room_id', $roomId)
            ->select();

        // 通过 GatewayClient 推送消息给所有在线成员
        try {
            \GatewayClient\Gateway::$registerAddress = '127.0.0.1:1236';
            $messageData = json_encode([
                'type' => 'group_chat',
                'room_id' => $roomId,
                'message_id' => $messageId,
                'sender_id' => $senderId,
                'content' => $content,
                'create_time' => time()
            ]);

            foreach ($members as $member) {
                if ($member['user_id'] != $senderId && \GatewayClient\Gateway::isUidOnline($member['user_id'])) {
                    \GatewayClient\Gateway::sendToUid($member['user_id'], $messageData);

                    // 更新未读计数
                    Db::name('chat_unread')
                        ->where('user_id', $member['user_id'])
                        ->where('room_id', $roomId)
                        ->setInc('unread_count', 1);
                }
            }
        } catch (\Exception $e) {
            // 记录日志，不影响消息发送结果
            	hink\Log::error('Gateway推送失败: ' . $e->getMessage());
        }

        return json([
            'code' => 0,
            'msg' => '发送成功',
            'data' => [
                'message_id' => $messageId,
                'room_id' => $roomId,
                'content' => $content,
                'create_time' => time()
            ]
        ]);
    }

    /**
     * 获取群聊消息列表
     * @param int $roomId 房间ID
     * @param int $page 页码
     * @param int $limit 每页数量
     */
    public function getGroupMessageList()
    {
        $roomId = $this->request->param('room_id/d');
        $page = $this->request->param('page/d', 1);
        $limit = $this->request->param('limit/d', 20);
        $userId = $this->auth->id;

        if (!$roomId) {
            return json(['code' => 1, 'msg' => '参数缺失']);
        }

        // 验证房间是否存在且当前用户是房间成员
        $isMember = Db::name('chat_room_members')
            ->where('room_id', $roomId)
            ->where('user_id', $userId)
            ->find();

        if (!$isMember) {
            return json(['code' => 2, 'msg' => '房间不存在或无权限']);
        }

        // 查询消息列表
        $messages = Db::name('chat_messages')
            ->where('room_id', $roomId)
            ->where('is_group', 1)
            ->order('create_time', 'asc')
            ->page($page, $limit)
            ->select();

        // 更新用户最后阅读时间
        $maxCreateTime = 0;
        foreach ($messages as $message) {
            if ($message['create_time'] > $maxCreateTime) {
                $maxCreateTime = $message['create_time'];
            }
        }

        if ($maxCreateTime > 0) {
            Db::name('chat_room_members')
                ->where('room_id', $roomId)
                ->where('user_id', $userId)
                ->update(['last_read_time' => $maxCreateTime]);

            // 重置未读计数
            Db::name('chat_unread')
                ->where('user_id', $userId)
                ->where('room_id', $roomId)
                ->update(['unread_count' => 0]);
        }

        return json([
            'code' => 0,
            'msg' => '获取成功',
            'count' => count($messages),
            'data' => $messages
        ]);
    }
}
